﻿using System;
using CID.Tests.Support.Configuration.Database;
using NHibernate;
using NUnit.Framework;

namespace CID.Tests.Support
{
    public abstract class BasePersistenceTests : BaseFunctionalTests
    {
        private static Initializer databaseInitializer = new Initializer();

        protected const int NotSavedId = 0;

        [TestFixtureSetUp]
        public void TestFixtureSetup()
        {
            sessionFactory = CID.Domain.Persistence.Configuration.CreateSessionFactory(Configuration.TestsConfiguration.DatabaseConnectionStringKey);
        }

        [TestFixtureTearDown]
        public void TestFixtureTearDown()
        {
            sessionFactory.Close();
            sessionFactory.Dispose();
            sessionFactory = null;
        }

        public override void SetUp()
        {
            base.SetUp();
            databaseInitializer.Initialize(SetupData);
        }

        protected virtual void SetupData()
        {
        }

        protected ISession OpenSession()
        {
            return sessionFactory.OpenSession();
        }

        protected void CleanSession(ISession session)
        {
            session.Flush();
            session.Close();
            session.Dispose();
        }

        private ISessionFactory sessionFactory = null;

        protected string GetRandomString(int maxLength = 0)
        {
            var result = Guid.NewGuid().ToString();
            if ((maxLength > 0) && (result.Length > maxLength)) result = result.Substring(0, maxLength);
            return result;
        }
    }
}
